﻿namespace Anley.DomainDrivenDesign.Contract.Extension;

/// <summary>
/// 实体扩展类
/// </summary>
public static class EntityExtension
{
    public delegate string TableNameMapperDelegate(Type type);
    public static TableNameMapperDelegate? TableNameMapper;
    private static readonly ConcurrentDictionary<RuntimeTypeHandle, string> TypeTableName = new ConcurrentDictionary<RuntimeTypeHandle, string>();

    /// <summary>
    /// 表名称
    /// </summary>
    /// <param name="type"></param>
    public static string GetTableName(this Type type)
    {
        if (TypeTableName.TryGetValue(type.TypeHandle, out string? name))
            return name;
        if (TableNameMapper != null)
            name = TableNameMapper(type);
        else
        {
            var tableAttrName =
                type.GetCustomAttribute<TableAttribute>(false)?.Name
                ?? (type.GetCustomAttributes(false).FirstOrDefault(attr => attr.GetType().Name == "TableAttribute") as dynamic)?.Name;
            if (tableAttrName != null)
                name = tableAttrName;
            else
            {
                name = type.Name + "s";
                if (type.IsInterface && name.StartsWith("I"))
                    name = name.Substring(1);
            }
        }
        TypeTableName[type.TypeHandle] = name;
        return name;
    }
}